import sys
import os
import tempfile
from moviepy.config import change_settings
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtCore import QUrl, Qt
from multiprocessing import freeze_support

from bridge.bridge import Bridge
from utils.tools import resource_path


moviepy_temp_dir = os.path.join(tempfile.gettempdir(), "moviepy_temp")
os.makedirs(moviepy_temp_dir, exist_ok=True)
change_settings({
    "IMAGEMAGICK_BINARY": resource_path(r"libs/ImageMagick-7.1.1-Q16-HDRI/magick.exe"),
    "TEMP_DIR": moviepy_temp_dir,
})
tempfile.tempdir = moviepy_temp_dir


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("AiMix")

        # 获取主屏幕的可用区域几何信息（考虑任务栏等系统区域）
        available_geometry = QApplication.primaryScreen().availableGeometry()
        screen_width = available_geometry.width()
        screen_height = available_geometry.height()

        self.setFixedSize(screen_width//2, screen_height//2)
        # 创建 WebEngineView 加载 HTML
        self.web_view = QWebEngineView(self)
        self.setCentralWidget(self.web_view)

        # TODO: 登录功能

        # 创建 WebChannel 连接前端与后端
        self.channel = QWebChannel()
        self.bridge = Bridge(self.web_view)  # 逻辑桥接对象
        # 注册桥接对象
        self.channel.registerObject("Bridge", self.bridge)  # 逻辑桥接对象

        self.web_view.page().setWebChannel(self.channel)
        # html_path = resource_path(r"view/login.html")
        html_path = resource_path(r"view\index.html")
        self.web_view.load(QUrl.fromLocalFile(os.path.abspath(html_path)))

        # 将窗口移动到屏幕左上角（0, 0）
        self.move(0, 0)

        # 确保窗口不会被最大化按钮最大化
        self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)


if __name__ == "__main__":

    freeze_support()
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
